//
//  AppDelegate.swift
//  weibo
//
//  Created by 长城 on 16/12/8.
//  Copyright © 2016年 dhsr. All rights reserved.
//

import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //取得用户授权显示通知[上方的提示条、声音、badgeNumber]
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.carPlay,.sound], completionHandler:
                {(success,error) in
                    print("授权" + (success ? "成功" : "失败"))
            })
        } else {
            let notifySettings = UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
            application.registerUserNotificationSettings(notifySettings)
        }
        
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        window?.rootViewController = WBMainViewController()
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        return true
    }
}

// MARK: - 从服务器加载应用程序信息
extension AppDelegate{
    func loadAppInfo(){
        //1.模拟异步 
        DispatchQueue.global().async {
            //1 url
            //let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            let url = Bundle.main.path(forResource: "main.json", ofType: nil)
            //2 data
            let data = NSData(contentsOfFile: url!)
            
            //3 写入磁盘
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            
            //直接保存至沙盒，不用回调，等待下一次程序加载
            data?.write(toFile: jsonPath, atomically: true)
            
            print("应用程序加载完毕..\(jsonPath)")
        }
    }
}
